package example.linklist_array.长度不一链表相加;

import java.util.LinkedList;

// NC40 两个链表生成相加链表
public class Demo5 {
    public static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode addInList(ListNode head1, ListNode head2) {
        //将 两个链表转换完毕后，进行相加
        ListNode list1 = revList(head1);
        ListNode list2 = revList(head2);
        int i = list1.val + list2.val;
        ListNode newNode = new ListNode(i % 10);
        ListNode tail = newNode;
        int ten = i / 10;
        ListNode temp1 = list1.next;
        ListNode temp2 = list2.next;
        while (temp1 != null && temp2 != null) {
            int val = ten + temp1.val + temp2.val;
            ListNode next = new ListNode(val % 10);
            ten = val / 10;
            tail.next = next;
            tail = next;
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        while (temp1 != null) {
            int val = ten + temp1.val;
            ListNode next = new ListNode(val % 10);
            ten = val / 10;
            tail.next = next;
            tail = next;
            temp1 = temp1.next;
        }
        while (temp2 != null) {
            int val = ten + temp2.val;
            ListNode next = new ListNode(val % 10);
            ten = val / 10;
            tail.next = next;
            tail = next;
            temp2 = temp2.next;
        }
        if (ten != 0) {
            tail.next = new ListNode(ten);
        }
        return revList(newNode);
    }

    /**
     * 链表反转
     *
     * @param head
     * @return
     */
    public ListNode revList(ListNode head) {
        ListNode current = head;
        ListNode prev = null;
        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    public static void main(String[] args) {

    }
}
